package com.qf.fengmimall.shiro;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.qf.fengmimall.user.entity.Users;
import com.qf.fengmimall.user.service.IUsersService;
import lombok.SneakyThrows;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;


/**
 * @author 刘欣
 * @createTime 2023/2/9 19:07
 * @description
 */
public class CustomRealm extends AuthorizingRealm {

    @Autowired
    public IUsersService userService;


    /**
     * 权限认证
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    /**
     * 身份认证
     *
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @SneakyThrows
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String username = (String) authenticationToken.getPrincipal();

        Users users = getUserFromDB(username);

        if (users == null) {
            throw new AuthenticationException("用户不存在");
        }

        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(users, users.getPassword(), ByteSource.Util.bytes(users.getSalt()), this.getName());

        return simpleAuthenticationInfo;
    }

    /**
     * 查询数据库
     *
     * @param username
     * @return users
     */
    private Users getUserFromDB(String username) {
        return userService.getOne(new LambdaQueryWrapper<Users>().eq(Users::getUsername, username));
    }
}


